from django import template
from pollster.models import *
from pollster.forms import *
from pollster.views import has_voted

register = template.Library()

class NewestPollNode(template.Node):
	def __init__(self, poll, submit):
		self.poll = poll
		self.submit = submit
	def render(self, context):
		if self.poll is None:
			return ''
		ip_address = context.get('ip_address', None)
		cookies = context.get('cookies', None)
		user = context.get('user', None)
		if not user.is_authenticated():
			user = None
		if has_voted(self.poll, user, cookies):
			form = None
			form_template = template.loader.select_template(['pollster/%s_results.html' % self.poll.id, 'pollster/results.html'])
		else:
			form = PollForm(self.poll)
			form_template = template.loader.select_template(['pollster/%s_form.html' % self.poll.id, 'pollster/form.html'])
		context.update({'pollster_form':form, 'submit': self.submit, 'poll': self.poll, 'choices':self.poll.choice_set.all()})
		return form_template.render(context)

@register.tag
def get_newest_poll(parser, token):
	bits = token.split_contents()
	if len(bits) == 2:
		submit= bits[1].strip('"')
	else:
		submit = None
	return NewestPollNode(Poll.objects.newest(), submit)